package com.example.dllo.keepdemo.dynamic.latest;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.dllo.keepdemo.R;
import com.example.dllo.keepdemo.base.BaseFragment;
import com.example.dllo.keepdemo.dynamic.DynamicDetailActivity;
import com.example.dllo.keepdemo.dynamic.bean.LatestBean;
import com.example.dllo.keepdemo.greendao.DynamicLatest;
import com.example.dllo.keepdemo.greendao.DynamicLatestDao;
import com.example.dllo.keepdemo.tools.CalculateTimeDifference;
import com.example.dllo.keepdemo.tools.DaoSingleton;
import com.example.dllo.keepdemo.tools.GsonRequest;
import com.example.dllo.keepdemo.tools.RefreshLayout;
import com.example.dllo.keepdemo.tools.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 16/1/8.
 */
public class LatestFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, RefreshLayout.OnLoadListener {
    private ListView listView;
    private LatestListViewAdapter latestListViewAdapter;
    private LatestBean latestBean;
    private RefreshLayout refreshLayout;
    private DynamicLatestDao dynamicLatestDao = DaoSingleton.getInstance().getDynamicLatestDao();
    private List<LatestBean.DataEntity> list;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_latest, container, false);
        listView = (ListView) view.findViewById(R.id.listview_fragment_latest);
        refreshLayout = (RefreshLayout) view.findViewById(R.id.swipe_fragment_latest);
        list = new ArrayList<>();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        refreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE);
        refreshLayout.setSize(SwipeRefreshLayout.LARGE);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadListener(this);
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        onRefresh();

        listView.setOnItemClickListener(this);

    }

    private void initData(String path) {
        latestBean = new LatestBean();
        GsonRequest<LatestBean> gsonRequest = new GsonRequest<LatestBean>(path, LatestBean.class, new Response.Listener<LatestBean>() {
            @Override
            public void onResponse(LatestBean response) {
                latestBean = response;
                for (int i = 0; i < response.getData().size(); i++) {
                    list.add(response.getData().get(i));
                }
                latestListViewAdapter = new LatestListViewAdapter(getActivity(), list, 2);
                listView.setAdapter(latestListViewAdapter);
                if (null != dynamicLatestDao.queryBuilder().list()) {
                    dynamicLatestDao.deleteAll();
                    addData(response);
                } else {
                    addData(response);
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                latestListViewAdapter = new LatestListViewAdapter(dynamicLatestDao.queryBuilder().list(), getActivity(), 1);
                listView.setAdapter(latestListViewAdapter);
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void addData(LatestBean response) {
        List<DynamicLatest> dynamicLatestList = new ArrayList<>();
        for (int i = 0; i < response.getData().size(); i++) {
            DynamicLatest dynamicLatest = new DynamicLatest();
            dynamicLatest.setContent(response.getData().get(i).getContent());
            dynamicLatest.setComment(response.getData().get(i).getComments() + "");
            dynamicLatest.setTime(CalculateTimeDifference.timeDifferenceUTC(response.getData().get(i).getCreated()));
            dynamicLatest.setCity(response.getData().get(i).getCity());
            dynamicLatest.setCount(response.getData().get(i).getMeta().getCount() + "");
            dynamicLatest.setMetaName(response.getData().get(i).getMeta().getName());
            dynamicLatest.setPraise(response.getData().get(i).getLikes() + "");
            dynamicLatest.setName(response.getData().get(i).getAuthor().getUsername());
            dynamicLatest.setImgHead(response.getData().get(i).getAuthor().getAvatar());
            dynamicLatest.setPicture(response.getData().get(i).getPhoto());
            dynamicLatestList.add(dynamicLatest);
        }

        dynamicLatestDao.insertInTx(dynamicLatestList);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), DynamicDetailActivity.class);
        intent.putExtra("id", latestBean.getData().get(position).get_id());
        startActivity(intent);
    }

    //下拉刷新
    @Override
    public void onRefresh() {
        refreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.clear();
                String url = "https://api.gotokeep.com/v1.1/timeline/trending?filter=true";
                initData(url);
                refreshLayout.setRefreshing(false);
            }
        }, 3000);
    }

    //上拉加载
    @Override
    public void onLoad() {
        refreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {

                String url = "https://api.gotokeep.com/v1.1/timeline/trending?filter=true?lastId=" + latestBean.getData().get(latestBean.getData().size() - 1).get_id();
                initData(url);
                latestListViewAdapter.notifyDataSetChanged();
                refreshLayout.setLoading(false);
            }
        }, 3000);
    }
}
